<script setup lang='ts'>
import type { FieldValues } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { useDelAccount, useEnableAccount, useGetAccountPage, useGetRoleList } from '@fl/api/mall-api'
import { SearchForm, SearchTable } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { ElButton } from 'element-plus'
import { cloneDeep } from 'lodash-es'

import AddOrUpdate from './add-or-update.vue'

const { meta: { isAdmin } } = useRoute()

const { createConfirmModal } = useMessage()
const id = ref('')
const visible = ref(false)

const initialState = {
    accountName: '',
    roleId: '',
}
const state = ref<FieldValues>(cloneDeep(initialState))

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))

const { data: propertyList } = useGetRoleList(isAdmin)
const { mutate: enableAccountMutate } = useEnableAccount(isAdmin)
const { mutate: delAccountMutate } = useDelAccount(isAdmin)
const propertyOptions = computed(() => (propertyList.value ?? []).map(x => ({ label: x.roleName, value: x.roleId })))
const params = computed(() => ({
    page: tablePage.value.currentPage,
    size: tablePage.value.pageSize,
    ...state.value,
}))

const { data: tableData, isLoading } = useGetAccountPage(params, isAdmin)

const records = ref()
watchEffect(() => {
    if (tableData.value) {
        records.value = cloneDeep(tableData.value.records)
        tablePage.value.total = tableData.value.total ?? 0
    }
})

const SWITCH_DICT = {
    0: {
        bg: 'bg-green-500',
        bool: true,
        label: '启用',
        msg: '禁用成功',
        tooltipLabel: '是否禁用该数据',
    },
    1: {
        bg: 'bg-red-500',
        bool: false,
        label: '禁用',
        msg: '启用成功',
        tooltipLabel: '是否启用该数据',
    },
}

const switchStatus = computed(() => (data: any) => {
    return SWITCH_DICT[data].bool
})

function changeStatus(row: any) {
    const tip = SWITCH_DICT[row.status].tooltipLabel
    createConfirmModal({ content: tip, onError: () => {
        console.log('操作取消！')
    }, onSuccess: () => {
        enableAccountMutate({
            status: Number(SWITCH_DICT[row.status].bool),
            userId: String(row.accountId),
        }, {
            onSuccess: () => {
                const msg = SWITCH_DICT[row.status].msg
                ElMessage.success(msg)
            },
        })
    } })
}

const columns = [
    {
        colProps: {
            span: 12,
        },
        label: '角色',
        options: propertyOptions,
        prop: 'roleId',
        valueType: 'select',
    },
    {
        colProps: {
            span: 12,
        },
        label: '账户名',
        prop: 'accountName',
    },
]

const gridOptions = reactive<VxeGridProps>({
    align: 'center',
    columnConfig: {
        resizable: true,
    },
    columns: [
        { field: 'accountName', title: '账户名' },
        { field: 'mobile', title: '手机号' },
        { field: 'roleName', title: '关联角色' },
        { field: 'createTime', title: '创建时间' },
        { field: 'status', slots: { default: 'status' }, title: '状态' },
        { slots: { default: 'operate' }, title: '操作' },
    ],
    data: [],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 800,
    keepSource: true,
    showOverflow: true,
    toolbarConfig: {
        slots: {
            buttons: 'toolbar_buttons',
        },
    },
})
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}
function search(values: FieldValues) {
    state.value = values
}
function reset() {
    state.value = cloneDeep(initialState)
    tablePage.value = cloneDeep(initialPage)
}
function showAdd() {
    id.value = ''
    visible.value = true
}
function edit(accountId: string) {
    id.value = accountId
    visible.value = true
}
function del(accountId: string) {
    createConfirmModal({ content: '是否确认删除？', onError: () => {
        console.log('操作取消！')
    }, onSuccess: () => {
        delAccountMutate(accountId, {
            onSuccess: () => {
                ElMessage.success('删除成功')
            },
        })
    } })
}
</script>

<template>
    <SearchTable v-bind="gridOptions"
                 v-model:pager="tablePage"
                 row-class-name="table-row-style"
                 :loading="isLoading"
                 :data="records"
                 @page-change="handlePageChange"
    >
        <template #toolbar_buttons>
            <div class="w-full">
                <el-row>
                    <el-col :span="12">
                        <ElButton type="primary"
                                  @click="showAdd"
                        >
                            <div class="i-ic:baseline-add size-16" />
                            新建账户
                        </ElButton>
                    </el-col>

                    <el-col :span="12">
                        <SearchForm v-bind="state"
                                    :columns="columns"
                                    submit-text="查询"
                                    label-width=""
                                    @submit="search"
                                    @reset="reset"
                        />
                    </el-col>
                </el-row>
            </div>
        </template>

        <template #status="{ row }">
            <span class="inline-block rounded-full h-8 w-8"
                  :class="SWITCH_DICT[row.status].bg"
            />
            {{ SWITCH_DICT[row.status].label }}
        </template>

        <template #operate="{ row }">
            <div class="text-#409EFF gap-15">
                <span class="cursor-pointer"
                      @click="edit(row.accountId)"
                >
                    编辑
                </span>

                <span class="ml-10 mr-10 cursor-pointer">
                    <el-switch :model-value="switchStatus(row.status)"
                               style="

--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                               inline-prompt
                               active-text="启用"
                               inactive-text="禁用"
                               @click="changeStatus(row)"
                    />
                </span>

                <span class="cursor-pointer"
                      @click="del(row.accountId)"
                >
                    删除
                </span>
            </div>
        </template>
    </SearchTable>

    <AddOrUpdate :key="id"
                 v-model:id="id"
                 v-model:visible="visible"
    />
</template>
